﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;

namespace Common.Utils
{
    public static class AliyunSmsApi
    {
        // 阿里云短信 API 的 RegionId 和 Endpoint
        private static readonly string regionId = "cn-hangzhou";
        private static readonly string endpoint = "dysmsapi.aliyuncs.com";

        // 阿里云短信 API 的 AccessKeyId 和 AccessKeySecret
        private static readonly string accessKeyId = "LTAI5tBP2oNiofWzXBWBTdqP";
        private static readonly string accessKeySecret = "JBpLVimDZoEwetVRQXNIiyMOKoYhnz";

        // 短信签名和模板 ID
        private static readonly string signName = "阿里云短信测试";
        private static readonly string templateCode = "SMS_154950909";

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phoneNumber">接收短信的手机号码</param>
        /// <param name="templateParam">短信模板中变量的替换值</param>
        /// <returns>是否发送成功，成功返回 true，失败返回 false。</returns>
        public static string SendSms(string phoneNumber, string templateParam)
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId,
             accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendSms";
            // request.Protocol = ProtocolType.HTTP;

            request.AddQueryParameters("PhoneNumbers", phoneNumber);
            request.AddQueryParameters("SignName", signName);
            request.AddQueryParameters("TemplateCode", templateCode);
            request.AddQueryParameters("TemplateParam", "{\"code\":\"" + templateParam + "\"}");
            request.AddQueryParameters("OutId", "");

            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                var content = System.Text.Encoding.Default.GetString(response.HttpResponse.Content);
                Console.WriteLine(content);
                return content;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return null;
        }
    }
}
